<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene" />
    <el-card>
      <div v-if="scene == 0">
        <el-button
          type="primary"
          icon="plus"
          :disabled="!categoryStore.c3Id"
          @click="addAttr"
        >
          添加属性
        </el-button>
        <el-table border :data="attrArr">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            align="center"
            width="120"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-tag v-for="(item, index) in row.attrValueList" :key="item.id">
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template #="{ row, $index }">
              <el-button
                type="success"
                icon="Edit"
                size="small"
                @click="updateAttr(row)"
              ></el-button>

              <el-popconfirm
                :title="`您确定要删除${row.attrName}`"
                width="250"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="small"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <!-- 展示添加属性与修改数据的结构 -->
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请输入属性名称"
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="plus"
          :disabled="!attrParams.attrName"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-button>取消</el-button>
        <el-table
          border
          style="margin: 10px 0"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            width="80"
            type="index"
            align="center"
            label="序号"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <!-- row:即为当前属性值对象 -->
              <el-input
                :ref="(vc: any) => (inputArr[$index] = vc)"
                placeholder="请输入属性值名称"
                v-model="row.valueName"
                v-if="row.flag"
                @blur="toLook(row, $index)"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                size="small"
                icon="delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="save"
          :disabled="
            attrParams.attrValueList.length > 0 &&
            attrParams.attrValueList[0].valueName != ''
              ? false
              : true
          "
        >
          保存
        </el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
// 获取接口方法
import {
  reqAttr,
  reqAddOrUpdateAttr,
  reqRemoveAttr,
} from '@/api/product/attr/index'
import type {
  AttrResponseData,
  Attr,
  ResponseData,
  AttrValue,
} from '@/api/product/attr/type'
// 获取分类仓库
import useCategoryStore from '@/store/modules/category'
import { ElMessage } from 'element-plus'
let categoryStore = useCategoryStore()

// 存储属性和属性值
let attrArr = ref<Attr[]>([])
// 定义卡片组件内容切换变量 0 展示添加与修改 1 展示结构与内容
let scene = ref<number>(0)
// 收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: '', // 新增的属性的名字
  attrValueList: [
    // 新增的属性值数组
  ],
  categoryId: '', // 三级分类的ID
  categoryLevel: 3, // 代表三级分类
})
// 存储对应的组件实例 el-input
let inputArr = ref<any>([])
// 监听仓库三级分类ID变化
watch(
  () => categoryStore.c3Id,
  () => {
    // 清空上一次查询的属性与属性值
    attrArr.value = []
    // 确保三级分类的id存在
    if (!categoryStore.c3Id) return
    getAttr()
  },
)

// 获取属性与属性值方法
const getAttr = async () => {
  // 获取分类的ID
  const { c1Id, c2Id, c3Id } = categoryStore
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code == 200) {
    attrArr.value = result.data
  }
}
// 添加属性与属性值方法
const addAttr = () => {
  // 每次添加前清空数据
  Object.assign(attrParams, {
    attrName: '', // 新增的属性的名字
    attrValueList: [
      // 新增的属性值数组
    ],
    categoryId: categoryStore.c3Id, // 收集三级分类ID
    categoryLevel: 3, // 代表三级分类
  })
  // 切换为添加与修改属性的结构
  scene.value = 1
}
// 修改属性与属性值方法
const updateAttr = (row: Attr) => {
  // 切换为添加与修改属性的结构
  scene.value = 1
  // 将已有的属性对象赋值给attrParam对象
  // ES6->Object.assign进行对象的合并
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
// 取消按钮的回调
const cancel = () => {
  scene.value = 0
}
// 添加属性值按钮的回调
const addAttrValue = () => {
  // 点击添加属性值按钮的回调，向数组添加一个属性值对象
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, // 控制每个属性值编辑模式和切换模式的切换
  })
  // 获取最后el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
// 保存按钮的回调
const save = async () => {
  // 发请求
  let result: ResponseData = await reqAddOrUpdateAttr(attrParams)
  if (result.code == 200) {
    // 切换场景
    scene.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.categoryId ? '修改成功' : '添加成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.categoryId ? '修改失败' : '添加失败',
    })
  }
}
// 属性值表单元素失去焦点
const toLook = (row: AttrValue, $index: number) => {
  // 非法情况判断1
  if (row.valueName.trim() == '') {
    // 删除调用调用对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  // 非法情况判断2
  let repeat = attrParams.attrValueList.find((item) => {
    // 切记把当前失去焦点的属性值对象从当前数组扣除判断
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    // 将重复的属性值删除
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }

  row.flag = false
}
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  // nextTick:响应式数据发生变化，获取更新后的DOM
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
// 删除某个已有的属性方法回调
const deleteAttr = async (attrId: number) => {
  // 发删除属性的请求
  let result: ResponseData = await reqRemoveAttr(attrId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
// 路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style scoped></style>
